package it.uniroma3.dia.mysql;

import it.uniroma3.dia.util.LoadProperties;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
//import java.sql.Statement;



public class CreateDB {
	private String url; 
	private String utente; 
	private String password;
	
	private String nomeDb;    
	
	private String utenti = "CREATE TABLE utenti (id int(11) NOT NULL AUTO_INCREMENT, screen_name text NOT NULL," +
			"dt_ultimo_aggiornamento date DEFAULT NULL, PRIMARY KEY (id))";
	
	private String amici = "CREATE TABLE amici (id int(11) NOT NULL AUTO_INCREMENT,username text NOT NULL,cod_utente int(11) NOT NULL,dt_rilevamento_amicizia date DEFAULT NULL," +
			"PRIMARY KEY (id),KEY newfk_30 (cod_utente),CONSTRAINT newfk_30 FOREIGN KEY (cod_utente) REFERENCES utenti (id))";
	
	private String cluster = "CREATE TABLE cluster (id int(11) NOT NULL AUTO_INCREMENT, cluster_name int(11) NOT NULL," +
			"utente text NOT NULL, rootuser text NOT NULL, PRIMARY KEY (id))";
	

	
	public CreateDB() {
		this.url = LoadProperties.getUrl();
		this.utente = LoadProperties.getNomeUtente();
		this.password = LoadProperties.getPassword();
		this.nomeDb = LoadProperties.getNomeDb();
	}

	private void createDb(){
		Connection con = null;
		PreparedStatement stat = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection(url, utente, password);

			stat = con.prepareStatement("CREATE DATABASE " + nomeDb); 
			stat.execute(); 
			
			con = Connector.getInstance().connetti();
			stat = con.prepareStatement(utenti);
			stat.execute();
			stat.close();
			stat = con.prepareStatement(amici);
			stat.execute();
			stat.close();
			stat = con.prepareStatement(cluster);
			stat.execute();
			stat.close();
			System.out.println("Database creato");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stat != null) {
				try {
					stat.close();
				} catch (SQLException e) {
				}
			}
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
				}
			}
		}
	}

	public static void main(String[] args) {
		CreateDB cr = new CreateDB();
		cr.createDb();
	}
}
